<template>
  <el-dialog :title="data.title" :close-on-click-modal="false" :visible.sync="visible" @close="close">
    <el-form :model="deptForm" :rules="rules" ref="deptForm">
      <el-form-item label="上级部门：" :label-width="formLabelWidth">
        <el-select v-model="deptForm.parentId" :disabled="isDisabled" filterable placeholder="请选择">
          <template v-for="item in deptOptions">
            <el-option
              :key="item.key"
              :disabled="item.key === data.deptId"
              :label="item.value"
              :value="item.key">
            </el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="部门名称：" :label-width="formLabelWidth" prop="deptName">
        <el-input v-model="deptForm.deptName" auto-complete="off"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <c-button type="primary" @click="submitForm">确 定</c-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    data: {
      type: Object
    }
  },
  data () {
    return {
      formLabelWidth: '120px',
      visible: true,
      deptOptions: [],
      deptForm: {
        deptName: '',
        parentId: this.data.parentId,
        deptId: ''
      },
      isDisabled: this.data.isDisabled,
      title: this.data.title,
      rules: {
        deptName: [
          ...this.$checkRules.dept.deptName
        ]
      }
    }
  },
  created () {
    this.$service.system.queryDeptList().then(response => {
      this.deptOptions = response.data
      this.deptForm.deptId = this.data.deptId
      this.deptForm.parentId = this.data.showId
      this.deptForm.deptName = this.data.deptName
    })
  },
  methods: {
    // 固定写法，每次加载都需要重置form
    close () {
      this.$emit('close')
    },
    submitForm (btn) {
      this.$refs.deptForm.validate((valid) => {
        if (valid) {
          this.$service.system.saveDept(this.deptForm).then(() => {
            this.visible = false
            this.$emit('ok')
          }).finally(() => {
            btn.isLoading(false)
          })
        } else {
          btn.isLoading(false)
        }
      })
    }
  }
}
</script>

<style>

</style>
